#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "sdkconfig.h"

static volatile bool button_pressed = false;
static const char *TAG = "INPUT TEST";
static void gpio_isr_handler(void *arg);

/*main task*/
void app_main(void)
{
    /*LED*/
    gpio_config_t ioConfig = {
        .pin_bit_mask = (1ull << CONFIG_BLINK_GPIO),
        .mode = GPIO_MODE_OUTPUT,
        .pull_up_en = 0,
        .pull_down_en = 0,
        .intr_type = GPIO_INTR_DISABLE,
    };
    gpio_config(&ioConfig);

    /*外部中断*/
    gpio_config_t ioConfig_irq = {
        .pin_bit_mask = (1ULL << CONFIG_MY_INPUT_IO),
        .mode = GPIO_MODE_INPUT,
        .pull_up_en = GPIO_PULLUP_ENABLE,
        .pull_down_en = GPIO_PULLDOWN_DISABLE,
        .intr_type = GPIO_INTR_ANYEDGE,
    };
    gpio_config(&ioConfig_irq);

    // 安装GPIO服务
    gpio_install_isr_service(0);
    // 配置GPIO中断类型，并注册中断服务函数
    gpio_set_intr_type(CONFIG_MY_INPUT_IO, GPIO_INTR_ANYEDGE);
    gpio_isr_handler_add(CONFIG_MY_INPUT_IO, gpio_isr_handler, NULL);

    while (1)
    {
        if (button_pressed)
        {
            ESP_LOGI(TAG, "botton press!");
            button_pressed = false;
            int level = gpio_get_level(CONFIG_MY_INPUT_IO);
            gpio_set_level(CONFIG_BLINK_GPIO, !level);
        }

        ESP_LOGI(TAG, "system run...");
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}

static void IRAM_ATTR gpio_isr_handler(void *arg)
{
    button_pressed = true;
}